/**
 * Created by hqh on 2016/8/2.
 */
var loadBool = true,    //列表数据请求是否完成标识
    perPage = 15;       //列表每页显示条数

//页面初始化
$(function(){
    showChargeList();

    // 查询手续费列表
    $('#query').click(function(){
        showChargeList();
    });

    //清空查询条件 按钮
    $('#clear').click(function(){
        clear();
        showChargeList();
    });
});

//清空查询条件
function clear(){
    $('#operaCenter,#transMotorcade,#carLicense,#driverName,#driverPhone,#circuitName').val('');
}

//显示手续费列表 从第1条记录开始
function showChargeList(){
    $("#curPage").text(1);
    $("#pages").text(1);
    getCurPage(1);
}

//获取当前活动页的手续费列表数据
function getCurPage(curPage){
    if(!loadBool){
        return;
    }
    else{
        loadBool = false;
        $('#chargeList').empty();
        var loadingIndex = layer.load(2, {
            shade: [0.1, '#fff']    //0.1透明度的白色背景
        });
        var data = JSON.stringify({
            'start_pos':(curPage-1)*perPage,
            'limit':perPage,
            'oc_name':$('#operaCenter').val(),
            'om_name':$('#transMotorcade').val(),
            'car_NO':$('#carLicense').val(),
            'driver_name':$('#driverName').val(),
            'driver_phone':$('#driverPhone').val(),
            'line_name':$('#circuitName').val()
        });
        $.ajax({
            type: "POST",
            url: "/chargemanager/glist",
            data:data,
            dataType: "json",
            success: function (res){
                console.log(res);
                layer.close(loadingIndex);
                if(res.status==0){
                    console.log('手续费列表：'+JSON.stringify(res));
                    var pageNum = Math.ceil(res.result.total/perPage);
                    $("#pages").text(pageNum);
                    $('#curPage').text(curPage);
                    for(var i=0, list=res.result.list; i<list.length; i++){
                        for(var key in list[i]){
                            if(list[i][key] == undefined || list[i][key] == null){
                                list[i][key] = " ";
                            }
                        }
                        var item = '<tr>' +
                            '<td style="display:none">'+list[i].id+'</td>' +
                            '<td>'+list[i].oc_name+'</td>' +
                            '<td>'+list[i].om_name+'</td>' +
                            '<td>'+list[i].car_NO+'</td>' +
                            '<td>'+list[i].driver_phone+'</td>' +
                            '<td>'+list[i].driver_name+'</td>' +
                            '<td>'+list[i].line_name +'</td>' +
                            '<td>'+list[i].line_id+'</td>' +
                            '<td>'+list[i].commission_3+'</td>' +
                            '<td>'+list[i].commission_0+'</td>' +
                            '<td>'+list[i].commission_1+'</td>' +
                            '<td>'+list[i].commission_2+'</td>' +
                            '<td>'+list[i].create_time+'</td>' +
                            '<td><a class="modify" href="javascript:void(0);" title="">修改</a> <a class="del" href="javascript:void(0);" title="">删除</a></td>' +
                            '</tr>';
                        $('#chargeList').append(item);
                    }
                }
                else{
                    bbx_alert_error(data.message);
                }
                loadBool = true;
            },
            error: function (xhr, status, error) {
                layer.close(loadingIndex);
                bbx_alert_error('出错啦~');
                loadBool = true;
            }
        });
    }
}

$(document).ready(function(){
    //显示上一页
    $('#lastPage').click(function(){
        var curPage = parseInt($("#curPage").text());
        if(curPage<=1){
            return;
        }
        else{
            getCurPage(curPage-1);
        }
    });

    //显示下一页
    $('#nextPage').click(function(){
        var curPage = parseInt($("#curPage").text()),
            totalpage = parseInt($('#pages').text());
        if(curPage==totalpage){
            return;
        }
        else{
            getCurPage(curPage+1);
        }
    });

    //修改手续费 弹框
    $('#chargeList').delegate('.modify','click',function(){
        var $infoList = $(this).parents('tr').find('td'),
            dataInfo = {
                "id": $infoList.eq(0).text(),
                "driver_name":$infoList.eq(5).text(),
                "car_NO":$infoList.eq(3).text(),
                "driver_phone":$infoList.eq(4).text(),
                "line_name":$infoList.eq(6).text(),
                "line_id":$infoList.eq(7).text(),
                "commission_0":$infoList.eq(9).text(),
                "commission_1":$infoList.eq(10).text(),
                "commission_2":$infoList.eq(11).text(),
                "commission_3":$infoList.eq(8).text()
            };
        var content = '<div class="modifyCharge">' +
            '<div class="form-inline">' +
            '<div class="form-group">' +
            '<label class="form-label-left" for="">司机:</label>' +
            '<span class="form-text-lg">' + dataInfo.driver_name + '</span>' +
            '<span class="form-text-lg">' + dataInfo.car_NO + '</span>' +
            '<span class="form-text-lg">' + dataInfo.driver_phone + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="form-inline">' +
            '<div class="form-group">' +
            '<label class="form-label-left" for="">线路:</label>' +
            '<span class="form-text-lg">' + dataInfo.line_name +'</span>' +
            '<span class="form-text-lg">' + dataInfo.line_id + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="form-inline">' +
            '<div class="form-group charge-percent">' +
            '<label class="form-label-left">手续费比例:</label>' +
            '<div class="charge-detail">' +
            '拼车：<input type="text" class="form-control" id="charge1" name="charge" value="' + dataInfo.commission_0 + '">% &nbsp;&nbsp;<i class="mandatory"></i><br/>' +
            '包车：<input type="text" class="form-control" id="charge2" name="charge" value="' + dataInfo.commission_1 + '">% &nbsp;&nbsp;<i class="mandatory"></i><br/>' +
            '寄件：<input type="text" class="form-control" id="charge3" name="charge" value="' + dataInfo.commission_2 + '">% &nbsp;&nbsp;<i class="mandatory"></i><br/>' +
            '市内：<input type="text" class="form-control" id="charge4" name="charge" value="' + dataInfo.commission_3 + '">% &nbsp;&nbsp;<i class="mandatory"></i><br/>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="bot-button bot-two-button">' +
            '<input id="modify" class="btn btn-lg-blue" type="button" value="确定">' +
            '<input id="cancel" class="btn btn-lg-blue" type="button" value="取消">' +
            '</div>' +
            '</div>';
        layer.open({
            type:1,
            skin:'layui-layer-rim',
            area:['320px, auto'],
            title: '修改手续费策略',
            content: content,
            success: function(layero,index){
                modifyCharge(layero,index,dataInfo.id);
            }
        });
    });
});

//修改手续费
function modifyCharge(layero,index,id){
    layero.find('input[name="charge"]').on('keyup',function(){
        onlyNumber2(this);
    });
    layero.find('input[name="charge"]').on('input',function(){
        onlyNumber2(this);
    });
    layero.find('#modify').click(function(){
        // layer.close(index);
        //检查输入的数值范围: 0-100正数，不为空格，允许小数
        if(!checkCharge(layero.find('#charge1'),layero.find('#charge2'),layero.find('#charge3'),layero.find('#charge4'))){
            return;
        }
        else{
            var curPage = parseInt($('#curPage').val()),
                data =JSON.stringify({
                    "id": Number(id),
                    "commission_0":Number(layero.find('#charge1').val()),
                    "commission_1":Number(layero.find('#charge2').val()),
                    "commission_2":Number(layero.find('#charge3').val()),
                    "commission_3":Number(layero.find('#charge4').val())
                });
            console.log(data);
            $.ajax({
                type: "POST",
                url: "/chargemanager/modify",
                data:data,
                dataType: "json",
                success: function (res){
                    console.log(res);
                    if(res.status==0){
                        layer.msg('修改成功！', {icon: 1, time: 1000}, function () {
                            layer.close(index);
                            showChargeList();
                        });
                    }
                    else{
                        bbx_alert_error('修改失败！');
                    }
                },
                error: function (xhr, status, error) {
                    console.log(error);
                    bbx_alert_error('出错啦~');
                }
            });
        }
    });

    layero.find('#cancel').click(function(){
        layer.close(index);
    });
}

//限制只能输入小数点和数字
function onlyNumber(obj){
    obj.value = obj.value.replace(/[^\d.]/g,"");       //先把非数字的都替换掉，除了数字和.
    obj.value = obj.value.replace(/^\./g,"");       //必须保证第一个为数字而不是.
    obj.value = obj.value.replace(/\.{2,}/g,".");       //保证只有出现一个.而没有多个.
    obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");      //保证.只出现一次，而不能出现两次以上
}
//限制只能输入数字
function onlyNumber2(obj){
    obj.value = obj.value.replace(/[^\d]/g,"");       //先把非数字的都替换掉，除了数字
}

//检查输入的值范围在0-100之间,并且不能为空
function checkCharge() {
    for(var i=0;i<arguments.length;i++){
        var value = arguments[i].val();
        if(value == '') {
            arguments[i].next('i').text('不能为空');
            return false;
        }
        else if(parseFloat(value) < 0 || parseFloat(value) > 100 || value.substr(value.length - 1, value.length) == '.') {
            arguments[i].next('i').text('请输入0-100之间的整数');
            return false;
        }
        else{
            arguments[i].next('i').text('');
        }
    }
    return true;
}
function checkCharge2() {
    for(var i=0;i<arguments.length;i++){
        var value = arguments[i].val();
        if(value == '') {
            bbx_alert_error('手续费不能为空，请重新输入');
            return false;
        }
        else if(parseFloat(value) < 0 || parseFloat(value) > 100 || value.substr(value.length - 1, value.length) == '.') {
            bbx_alert_error('手续费范围为0-100之间的整数');
            return false;
        }
        else{
            arguments[i].next('i').text('');
        }
    }
    return true;
}

//删除手续费 按钮
$(function(){
    $('#chargeList').delegate('.del','click',function() {
        var id = $(this).parents('tr').find('td').eq(0).text(),
            _this = this;
        bbx_confirm2('确认删除此条记录?',function(){
            // $(_this).parents('tr').remove();
            delCharge(id,_this);
        },function(){
            //do nothing
        });
    });
});

//删除手续费
function delCharge(id,target){
    var data = JSON.stringify({"id":parseInt(id)});
    // bbx_alert_warning('页面已删除,后台尚未提供删除接口,刷新后仍保留。');
    console.log('删除参数:' +data);
    $.ajax({
        type: "POST",
        url: "/chargemanager/del",
        data:data,
        dataType: "json",
        success: function (res){
            console.log('删除返回结果:' + res);
            if(res.status==0){
                layer.msg('删除成功！', {icon:1,time:1000}, function () {
                    $(target).parents('tr').remove();
                });
            }
            else{
                bbx_alert_error('删除失败！')
                console.log(res.message);
            }
        },
        error:function(xhr, status, error){
            bbx_alert_error('出错啦~');
        }
    });
}

//新增手续费 弹出页面
$(function(){
    $('#addCharge').click(function(){
        var index = layer.open({
            type: 2,
            title: false,
            closeBtn: 0, //不显示关闭按钮
            maxmin: false,
            content: '/chargeadd/chadd',
            success: function (layero, index) {
                initAddCharge(layero);
            }
        });
        layer.full(index);
    });
});


//新增手续费 初始页面
function initAddCharge(layero){
    var layerIframe = layero.find('iframe:first-child').contents();
    back(layerIframe);
    addCharge(layerIframe);
}

//返回上一页 关闭新增手续费页面
function back(layerIframe) {
    layerIframe.on('click', "#back", function () {
        layer.closeAll();
    });
}

//新增手续费 执行函数
function addCharge(layerIframe){
    layerIframe.find('input[name="charge"]').on('keyup',function(){
        onlyNumber2(this);
    });
    layerIframe.find('input[name="charge"]').on('input',function(){
        onlyNumber2(this);
    });

    layerIframe.find('#confirm').click(function() {
        // layer.closeAll();
        //检查输入的数值范围: 0-100整数，不为空格
        if (!checkCharge2(layerIframe.find('#charge1'), layerIframe.find('#charge2'), layerIframe.find('#charge3'), layerIframe.find('#charge4'))) {
            return;
        }
        else {
            var driverList = layerIframe.find('#driverList tr'),
                circuitList = layerIframe.find('#circuitList tr'),
                driversInfo = [],
                circuitsInfo = [];
            for (var i = 0; i < driverList.length; i++) {
                var driverTarget = driverList.eq(i).find('td'),
                    driverItem = {
                        "oc_code": driverTarget.eq(0).text(),
                        "oc_name": driverTarget.eq(1).text(),
                        "om_code": driverTarget.eq(2).text(),
                        "om_name": driverTarget.eq(3).text(),
                        "car_NO": driverTarget.eq(4).text(),
                        "driver_id": driverTarget.eq(5).text(),
                        "driver_phone": driverTarget.eq(6).text(),
                        "driver_name": driverTarget.eq(7).text()
                    };
                driversInfo.push(driverItem);
            }
            console.log(driversInfo);
            for (var j = 0; j < circuitList.length; j++) {
                var circuitTarget = circuitList.eq(j).find('td'),
                    circuitItem = {
                        "line_id": circuitTarget.eq(1).text(),
                        "line_name": circuitTarget.eq(0).text()
                    };
                circuitsInfo.push(circuitItem);
            }
            console.log(circuitsInfo);
            //司机和线路信息两者都不能为空
            if(driversInfo.length==0){
                bbx_alert_error('请选择司机信息！');
                return;
            }
            else if(circuitsInfo.length==0){
                bbx_alert_error('请选择线路信息！');
                return;
            }
            else{
                var data = {
                    "driver_info": driversInfo,
                    "line_info": circuitsInfo,
                    "commission_0": Number(layerIframe.find('#charge1').val()),
                    "commission_1": Number(layerIframe.find('#charge2').val()),
                    "commission_2": Number(layerIframe.find('#charge3').val()),
                    "commission_3": Number(layerIframe.find('#charge4').val())
                };
                // console.log('已选司机数据：'+JSON.stringify(driversInfo));
                // console.log('已选线路数据：'+JSON.stringify(circuitsInfo));
                // var loadingIndex = layer.load(2, {
                //     shade: [0.1, '#fff']    //0.1透明度的白色背景
                // });
                var driversArr = divideData(data['driver_info'],10),
                    linesArr = divideData(data['line_info'],10),
                    offset = [];
                for(var k=0; k<driversArr.length; k++){
                    for(var v=0; v<linesArr.length; v++){
                        var _offset = [];
                        _offset.push(k);
                        _offset.push(v);
                        offset.push(_offset);
                    }
                }
                console.log('偏移量为：'+JSON.stringify(offset));
                var loadingIndex = layer.msg('正在添加,请耐心等待...', {icon: 16, time: 3600000, shade: [0.5, '#fff']});
                partAddCharge(data,loadingIndex,driversArr,linesArr,offset,0);
            }
        }
    });

    layerIframe.find('#cancel').click(function(){
        layer.closeAll();
    });
}

//数据分组，每组数量最多m个
function divideData(data,m){
    var total = data.length,
        num = Math.ceil(total/m);
    var group = [];
    for(var i=0; i<num; i++){
        var _data = [];
        for(var j=i*m; j<(i*m)+m; j++){
            if(j > total-1){
                break;
            }
            else{
                _data.push(data[j]);
            }
        }
        console.log('分组数据--第'+i+'组数据：'+JSON.stringify(_data));
        group.push(_data);
    }
    return group;
}

//分批次发送添加手续费时传递的参数
var completeFlag = false;
function partAddCharge(data,loadingIndex,driversArr,linesArr,offset,num) {
    console.log('执行函数前,completeFlag值：'+completeFlag);
    var maxLimit = offset.length;
    if (num == maxLimit - 1) {
        completeFlag = true;
    }
    else if(num >= maxLimit){
        return;
    }
    var _data = JSON.stringify({
        "driver_info": driversArr[offset[num][0]],
        "line_info": linesArr[offset[num][1]],
        "commission_0": data['commission_0'],
        "commission_1": data['commission_1'],
        "commission_2": data['commission_2'],
        "commission_3": data['commission_3']
    });
    console.log('分批发送数据第' + (offset[num][0] * linesArr.length + offset[num][1]) + '次,,' + '发送参数为：' + _data);
    $.ajax({
        type: "POST",
        url: "/chargemanager/add",
        data: _data,
        async: true,
        dataType: "json",
        success: function (res) {
            console.log(res);
            if (res.status == 0) {
                if (completeFlag == true) {
                    console.log('批量传输全部完成...');
                    layer.close(loadingIndex);
                    layer.msg('添加成功！', {icon: 1, time: 500}, function () {
                        layer.closeAll();
                        clear();
                        showChargeList();
                    });
                }
                else {
                    console.log('第'+(num+1)+'组ajax数据, ajax返回成功');
                    console.log('completeFlag值：'+completeFlag);
                    partAddCharge(data, loadingIndex, driversArr, linesArr, offset, num+1);
                }
            }
            else {
                layer.close(loadingIndex);
                bbx_alert_error('添加失败！');
            }
        },
        error: function (xhr, status, error) {
            layer.close(loadingIndex);
            bbx_alert_error('出错啦~');
        }
    });
}
